<?php

require_once(app_path() . '/pay/mns/mns-autoloader.php');

use AliyunMNS\Client;
use AliyunMNS\Topic;
use AliyunMNS\Constants;
use AliyunMNS\Model\MailAttributes;
use AliyunMNS\Model\SmsAttributes;
use AliyunMNS\Model\BatchSmsAttributes;
use AliyunMNS\Model\MessageAttributes;
use AliyunMNS\Exception\MnsException;
use AliyunMNS\Requests\PublishMessageRequest;

class Sms {
	
	private $config = array();
	
	function __construct($config){
		$this->config = $config;
	}
	
// 	function Sms() {
		
// 	}
	
	public function send($phone,$templateCode,$params){
		$client = new Client($this->config["endpoint"], $this->config["key"], $this->config["secret"]);
		
		$topic = $client->getTopicRef($this->config["topic_name"]);
		
		
		$batchSmsAttributes = new BatchSmsAttributes($this->config["sign_name"], $templateCode);
		
		
		//$params中的值必须是字符串
		$batchSmsAttributes->addReceiver($phone, $params);
		$messageAttributes = new MessageAttributes(array($batchSmsAttributes));
		
		/**
		 * Step 4. 设置SMS消息体（必须）
		 *
		 * 注：目前暂时不支持消息内容为空，需要指定消息内容，不为空即可。
		 */
		$messageBody = "smsmessage";
		/**
		 * Step 5. 发布SMS消息
		 */
		$request = new PublishMessageRequest($messageBody, $messageAttributes);
		try {
			$res = $topic->publishMessage($request);
			Log::info("sms result => ",
			array('msgId' => $res->getMessageId(),
				"success"=>$res->isSucceed(),
				"msgBody" => $res->getMessageBodyMD5()
			));
			return $res->isSucceed();
		} catch (MnsException $e) {
// 			Log::info(date ( "Y-m-d H:i:s" ) . "  " . $text );
			Log::error($e);
		}
	}
}

?>